#!/bin/bash


action=$1
dir2share=$2
SRVNAM=ftpd
srvprt=5557
secDelay=1
srvpid=$(ps aux|grep "nmftpsrv -p ${srvprt}"|grep -v grep|awk '{print $2}')
echo srvpid:$srvpid

if [ "$action" == "" ]; then
	action=stop
fi

if [ "$dir2share" == "" ]; then
	dir2share="~/"
fi

function stop() {
	if [ "$srvpid" == "" ]; then
		gxmessage -title "信息" "${SRVNAM}未运行"  -center
		exit 0
	else
		kill $srvpid
		rlt=$?
		if [ $rlt -ne 0 ]; then
			gxmessage -title "错误" "${SRVNAM}停止失败"  -center -fg red
			exit $rlt
		fi

		gxmessage -title "信息" "${SRVNAM}已停止"  -center
		exit $rlt
	fi
}

function start() {
	if [ "$srvpid" == "" ]; then
		cd ~
		exec ${app_home}/nmftpsrv -p ${srvprt} -c gb18030 -d ${dir2share}
	else
		echo "已经启动"
	fi
}

function check() {
	sleep $secDelay
	srvpid=$(ps aux|grep "nmftpsrv -p ${srvprt}"|grep -v grep|awk '{print $2}')

	if [ "$srvpid" == "" ]; then
		gxmessage -title "错误" "${SRVNAM}启动失败"  -center -fg red
		exit
	fi

	cat <<- EOF > /tmp/ip.txt
		${dir2share} 已通过ftp对外共享
		================================
		您可以在电脑上使用文件浏览器等ftp客户端工具访问,
		运行如下指令即可读写此模拟器内的文件:

	EOF

	/exbin/tools/vm_ip2link.sh "explorer  ftp://" ":${srvprt}">>/tmp/ip.txt

	cat <<- EOF >> /tmp/ip.txt

		在windows电脑端上写ftp文件的2种方式:
		1). 点击开始，运行，粘贴以上地址,然后回车
		2). 安装专业的ftp客户端工具

		注：请匆将隐私类文件进行共享! 共享功能不使用时，请立即关闭。

		关闭这个窗口不影响功能.

	EOF

	gxmessage -title "${SRVNAM}" -file /tmp/ip.txt -center
}


case "${action}" in
	"stop")
		stop
		;;
	"start")
		tmpfile=/tmp/${SRVNAM}.desktop
		cat <<- EOF > ${tmpfile}
			[Desktop Entry]
			Name=${SRVNAM}_check
			GenericName=${SRVNAM}_check
			Exec=$0 check
			Terminal=false
			Type=Application
		EOF
		xopen ${tmpfile}
		# nohup $0 check &
		# bg 	     > /tmp/bg.txt 2>&1
		# jobs     >>/tmp/bg.txt 2>&1
		# disown -a>>/tmp/bg.txt 2>&1
		start
		;;
	"check")
		check
		;;
esac

